//
//  PMGlobal.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/20/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "PMGlobal.h"
#import "AppManager.h"

#import "RFRequest.h"
#import "RFService.h"
#import "RFResponse.h"
#import "JSONKit.h"

#import "Reachability.h"
#import "WaitTooles.h"

#import "WebServiceManager.h"
static PMGlobal *_gInstance = nil;

@interface PMGlobal(){
    
}

@end

@implementation PMGlobal

+ (PMGlobal *)getInstance {
    @synchronized( [PMGlobal class] ){
        if(!_gInstance)
            _gInstance = [[self alloc] init];
        return _gInstance;
    }
    return nil;
}

+ (id)alloc {
    @synchronized ([PMGlobal class]){
        NSAssert(_gInstance == nil,
                 @"Attempted to allocated a second instance");
        _gInstance = [super alloc];
        return _gInstance;
    }
    return nil;
}

- (id)init {
    self = [super init];
    if (self) {
        m_bImageEnable = NO;
    }
    return self;
}

- (UIFont *)getPadFont:(float)size{
    return [UIFont fontWithName:@"STHeitiTC-Medium" size:size];
}
- (UIFont *)getPhoneFont:(float)size{
    return [UIFont fontWithName:@"STHeitiTC-Medium" size:size];
}

- (UIFont *)getBoldPadFont:(float)size{
    return [UIFont fontWithName:@"STHeitiTC-Medium" size:size];
}
- (UIFont *)getBoldPhoneFont:(float)size{
    return [UIFont fontWithName:@"STHeitiTC-Medium" size:size];
}

- (NSString *)getDomainName{
//    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
//    NSString *url = [def stringForKey:@"url_preference"];
//    NSString *port = [def stringForKey:@"port_preference"];
//    
//    NSString *address = [NSString stringWithFormat:@"%@:%@",url,port];
    NSString *s = [[[WebServiceManager sharedManager] baseURL] stringByDeletingLastPathComponent];
    s = [s stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
    return s;
}

- (NSString *)getServerURL{
    NSString *s = [[self getDomainName] stringByAppendingPathComponent:@"Service.aspx"];
    return s;
}
- (NSString *)getImageURL{
    NSString *s = [[self getDomainName] stringByAppendingPathComponent:@"info"];
    s = [s stringByReplacingOccurrencesOfString:@"http:/" withString:@"http://"];
    return s;
}

- (void)isWifiOn:(DMCompletion)completion{
    
#ifdef ENABLE_LAN_CHECK
    RFRequest *r = [RFRequest requestWithURL:[NSURL URLWithString:[[WebServiceManager sharedManager] baseURL]]
                                        type:RFRequestMethodGet
                      resourcePathComponents:nil];
    [RFService execRequest:r completion:^(RFResponse *response){
        if ([response.stringValue isEqualToString:LAN_MARK]) {
            completion(response.stringValue);
        }else{
            completion(nil);
        }
        
    }];
#else
    
    
    dispatch_queue_t wifi_queue = dispatch_queue_create("com.yx.pm.wifi", NULL);
    dispatch_async(wifi_queue, ^(void) {
        
        Reachability* wifiReach = [Reachability reachabilityForInternetConnection];
        
        NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (netStatus==ReachableViaWiFi) {
                completion(@"");
            }else{
                completion(nil);
            }
        });
        
    });
#endif
}


- (NSArray *)getImageConfig{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSArray *config = [def objectForKey:@"config"];
    return config;
}
- (void)saveImageConfig:(NSArray *)config{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:config forKey:@"image_config"];
    [def synchronize];
}

- (NSString *)getImageConfigUrl:(NSString *)type{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSArray *config = [def objectForKey:@"image_config"];
    
    for (NSDictionary *d in config) {
        if ([[d objectForKey:@"PicType"] isEqualToString:type]) {
            NSString *url = [d objectForKey:@"url"];
            NSString *path = [[[PMGlobal getInstance] getImageURL] stringByAppendingPathComponent:url];
            return path;
        }
    }
    return @"";
}

//-(void) restService:(RFService*)svc didFinishWithResponse:(RFResponse*)response{
//    
//}

- (int)networkFlag{
    return m_iNetwork;
}

- (void)setNetworkFlag:(int)flag{
    m_iNetwork = flag;
}

- (BOOL)isImageEnable{
    return m_iNetwork || m_bImageEnable;
}

- (void)enableImage:(BOOL)enable{
    m_bImageEnable = enable;
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:[NSNumber numberWithBool:enable] forKey:@"ShowPhoto"];
    [def synchronize];
}

- (NSString *)getSettingBar_TypeName:(eSettingBar_Type)type{
    switch (type) {
        case eSettingBar_Type_Admin:
            return @"管理员页面";
#ifdef SHOP_VERIFY_ENABLE
        case eSettingBar_Type_Shopcheck:
            return @"店铺检查";
        case eSettingBar_Type_Shopveri:
            return @"店铺审核";
#endif
        case eSettingBar_Type_Update:
            return @"更新商品资料";
        case eSettingBar_Type_Version:
        {
            NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
            NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
            return [NSString stringWithFormat:@"版本号:%@",appVersion];
        }
            
        default:
            break;
    }
    
    return @"";
}

-(NSString *)gettype
{
    NSString *bundlePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:CUSTOMER_PATH];
    NSString *plistname = [NSString stringWithFormat:@"%@.plist",CUSTOMER_NAME];
    NSString *filename = [bundlePath stringByAppendingPathComponent:plistname];
    NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:filename];
    return [d objectForKey:@"type"];
}

-(UIImage *)getnavigationbarimage
{
    UIImage *img;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        if ([[[PMGlobal getInstance]gettype]isEqualToString:@"type1"]) {
            img = [[UIHelper getInstance] getBundleImage:@"navigationBarios7type1.png"];
        }
        else
        {
            img = [[UIHelper getInstance] getBundleImage:@"navigationBarios7.png"];
        }
    }
    else
    {
        if ([[[PMGlobal getInstance]gettype]isEqualToString:@"type1"]) {
            img = [[UIHelper getInstance] getBundleImage:@"navigationBartype1.png"];
        }
        else
        {
            img = [[UIHelper getInstance] getBundleImage:@"navigationBar.png"];
        }
    }
    return img;
}

-(UIImage *)getretimage
{
    UIImage *img;
    if ([[[PMGlobal getInstance]gettype]isEqualToString:@"type1"]) {
        img = [[UIHelper getInstance] getBundleImage:@"type1_homepage.png"];
    }
    else
    {
        img = [[UIHelper getInstance] getBundleImage:@"homepage.png"];
    }
    return img;
}
@end

void runBlockAfterDelay( NSTimeInterval delay ,block completion){
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
                   dispatch_get_current_queue(), completion);
}

void showMessage( NSString *message ){
    [WaitTooles showHUDText:message];
    runBlockAfterDelay( 1.0, ^(){
        [WaitTooles removeHUD];
    });
}
